package com.example.xyxwebbackend001.controller;

import com.example.xyxwebbackend001.common.CommonResult;
import com.example.xyxwebbackend001.config.FileUploadConfig;
import com.example.xyxwebbackend001.model.DTO.CommentRequestDTO;
import com.example.xyxwebbackend001.model.DTO.PostRequestDTO;
import com.example.xyxwebbackend001.model.DTO.TPostsDTO;
import com.example.xyxwebbackend001.model.entity.TPosts;
import com.example.xyxwebbackend001.service.ComService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

//社区交流表
@RestController
@RequestMapping("/com")
public class ComController {
    @Autowired
    private ComService comService;

    @Autowired
    private FileUploadConfig fileUploadConfig;

    //    获取帖子列表
    @GetMapping("/thread/list")
    public CommonResult<Object> getThrList(@RequestParam Integer userId, @RequestParam(required = false) String cityId) {
        try {
            List<TPostsDTO> res = comService.getTPostList(userId, cityId);

            if(res != null) {
                return CommonResult.message(res);
            }
            return CommonResult.fail(200, "执行成功！");

        } catch (Exception e) {
            return CommonResult.error("系统异常：" + e.getMessage());
        }
    }
    // 新增用户维度统计接口
    @GetMapping("/post-stats/{userId}")
    public CommonResult<Map<String, Object>> getUserPostStats(@PathVariable Integer userId) {
        Map<String, Object> stats = comService.getUserPostStats(userId);
        return CommonResult.message(stats);
    }

    // 点赞或收藏操作
    @PostMapping("/toggle")
    public CommonResult<Boolean> toggleAction(
            @RequestParam(value = "actionType") String actionType,
            @RequestParam("postId") Integer postId
    ) {
        try {
            boolean newStatus = comService.toggleAction(actionType, postId);
            return CommonResult.message(newStatus);
        } catch (IllegalArgumentException e) {
            return CommonResult.fail(400, e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("操作异常：" + e.getMessage());
        }
    }

    // 新增评论接口
    @PostMapping("/comment")
    public CommonResult<Boolean> createComment(@RequestBody CommentRequestDTO request) {
        try {
            boolean result = comService.createComment(
                    request.getPostId(),
                    request.getUserId(),
                    request.getContent()
            );
            return CommonResult.message(result);
        } catch (IllegalArgumentException e) {
            return CommonResult.fail(400, e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("评论失败：" + e.getMessage());
        }
    }
    @DeleteMapping("/comment/{commentId}")
    public CommonResult<Boolean> deleteComment(@PathVariable Integer commentId) {
        try {
            boolean result = comService.deleteComment(commentId);
            return CommonResult.message(result);
        } catch (IllegalArgumentException e) {
            return CommonResult.fail(400, e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("删除失败：" + e.getMessage());
        }
    }

    @PostMapping("/thread/create")
    public CommonResult<Integer> createPost(@RequestBody TPosts post) {
        try {
            // 参数校验
            if (post.getUserId() == null) {
                return CommonResult.fail(400, "用户ID不能为空");
            }

            // 设置创建时间并保存
            post.setCreatedAt(LocalDateTime.now());
            comService.createPost(post);

            // 返回自动生成的ID
            return CommonResult.message(post.getTPostId());
        } catch (Exception e) {
            return CommonResult.error("创建失败：" + e.getMessage());
        }
    }
    // 上传图片
    @PostMapping("/thread/upload")
    public CommonResult<String> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("tPostId") Integer tPostId) {

        if (file.isEmpty()) {
            return CommonResult.fail(400, "文件不能为空");
        }

        try {
            File dir = new File(fileUploadConfig.getUploadComDir());
            if (!dir.exists()) dir.mkdirs();

            String originalName = file.getOriginalFilename();
            String fileExt = originalName.substring(originalName.lastIndexOf("."));
            String fileName = System.currentTimeMillis() + fileExt;

            File dest = new File(dir.getAbsolutePath() + File.separator + fileName);
            file.transferTo(dest);

            return CommonResult.message(fileName);
        } catch (IOException e) {
            return CommonResult.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("操作失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/thread/upload/delete/{fileId}")
    public CommonResult<Boolean> deleteUploadFile(
            @PathVariable String fileId,
            @RequestParam Integer tPostId) {
        try {
            File file = new File(fileUploadConfig.getUploadComDir(), fileId);

            if (file.exists()) {
                if (!file.delete()) {
                    return CommonResult.error("物理文件删除失败");
                }
                return CommonResult.success(true);
            }
            return CommonResult.fail(404, "文件不存在");

        } catch (Exception e) {
            return CommonResult.error("删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/thread/publish")
    public CommonResult<String> savePost(@RequestBody PostRequestDTO request) {
        try {
            // 参数校验
            if (request.getTitle() == null || request.getTitle().isEmpty()) {
                return CommonResult.fail(400, "标题不能为空");
            }
            Integer tPostId = request.getTPostId();
            String title = request.getTitle();
            String content = request.getContent();
            String imagPath = request.getImagePath();
            String place = request.getPlace();
            String tags = request.getTags();

            // 执行更新
            boolean result = comService.updatePost(tPostId, title, content, imagPath, place, tags);
            return CommonResult.tip(result ? "更新成功" : "更新失败");
        } catch (IllegalArgumentException e) {
            return CommonResult.fail(400, e.getMessage());
        } catch (Exception e) {
            return CommonResult.error("更新失败: " + e.getMessage());
        }
    }

}
